<?php
require dirname(__FILE__) . '/basics.php';

//menu fnction for Smarty template
/**
 * get HTML for building a hierarchical menu
 *
 * @param array $opts options
 *
 * @return string the html
 */
function Core_menuDisplay($opts = array()) {
	if (!function_exists('menuBuild')) { // menuBuild
		/**
		 * get recursive details of pages to build a menu
		 *
		 * @param int   $parentid the parent's ID
		 * @param int   $depth    current menu depth
		 * @param array $options  any further options
		 *
		 * @return string HTML of the sub-menu
		 */

		function menuBuild($parentid, $depth, $options) {
			$db = Database::getInstance();
			$PARENTDATA = Page::getInstance($parentid)->initValues();
			// { menu order
			$order = 'ord,name';
			if (isset($PARENTDATA->vars['order_of_sub_pages'])) {
				switch ($PARENTDATA->vars['order_of_sub_pages']) {
					case 1: // { alphabetical
						$order = 'name';
						if ($PARENTDATA->vars['order_of_sub_pages_dir']) {
							$order.=' desc';
						}
						break; // }
					case 2: // { associated_date
						$order = 'associated_date';
						if ($PARENTDATA->vars['order_of_sub_pages_dir']) {
							$order.=' desc';
						}
						$order.=',name';
						break; // }
					default: // { by admin order
						$order = 'ord';
						if ($PARENTDATA->vars['order_of_sub_pages_dir']) {
							$order.=' desc';
						}
						$order.=',name';
						break; // }
				}
			}
			// }
			$sql = "select id,name,type from pages where parent='" . $parentid
					. "' and !(special&2) order by $order";
			$rs = $db->dbAll($sql);
			
			/*
			  $md5=md5($sql);
			  $rs=Core_cacheLoad('pages', $md5, -1);
			  if ($rs===-1) {
			  $rs= $db->dbAll($sql);
			  Core_cacheSave('pages', $md5, $rs);
			  }
			 * 
			 */
			  if ($rs===false || !count($rs)) {
			  return '';
			  }
			
			$items = array();
			foreach ($rs as $r) {
				$item = '<li>';
				$page = Page::getInstance($r['id'])->initValues();
				$item.='<a class="menu menu-pid-' . $r['id'] . '" href="'
						. $page->getRelativeUrl() . '">'
						. htmlspecialchars($page->name) . '</a>';
				if ($submenus) {
					$item.=$submenus;
				}
				// }
				// { otherwise load sub-menus as usual
				else {
					$item.=menuBuild($r['id'], $depth + 1, $options);
				}
				// }
				$item.='</li>';
				$items[] = $item;
			}
			$options['columns'] = (int) $options['columns'];
			// { return top-level menu
			if (!$depth) {
				return '<ul>' . join('', $items) . '</ul>';
			}
			// }
			$s = '';
			if ($options['style_from'] == '1') {
				if ($options['background']) {
					$s.='background:' . $options['background'] . ';';
				}
				if ($options['opacity']) {
					$s.='opacity:' . $options['opacity'] . ';';
				}
				if ($s) {
					$s = ' style="' . $s . '"';
				}
			}
			// { return 1-column sub-menu
			if ($options['columns'] < 2) {
				return '<ul' . $s . '>' . join('', $items) . '</ul>';
			}
			// }
			// { return multi-column submenu
			$items_count = count($items);
			$items_per_column = ceil($items_count / $options['columns']);
			$c = '<table' . $s . '><tr><td><ul>';
			for ($i = 1; $i < $items_count + 1; ++$i) {
				$c.=$items[$i - 1];
				if ($i != $items_count && !($i % $items_per_column)) {
					$c.='</ul></td><td><ul>';
				}
			}
			$c.='</ul></td></tr></table>';
			return $c;
			// }
		}

	}
	//global $_languages;
	$c = '';
	//$md5_1=md5('menu_fg|'.print_r($opts, true).'|'.join(', ', $_languages));
	$options = array(
		'direction' => 0, // 0: horizontal, 1: vertical
		'parent' => 0, // top-level
		'background' => '', // sub-menu background colour
		'columns' => 1, // for wide drop-down sub-menus
		'opacity' => 0, // opacity of the sub-menu
		'type' => 0, // 0=drop-down, 1=accordion, 3=tree list
		'style_from' => 1, // inherit sub-menu style from CSS (0) or options (1)
		'state' => 0, // 2=expand current page,1=expand all,0=contract all
	);
	foreach ($opts as $k => $v) {
		if (isset($options[$k])) {
			$options[$k] = $v;
		}
	}
	if (!is_numeric($options['parent'])) {
		$r = Page::getInstanceByName($options['parent']);
		if ($r) {
			$options['parent'] = $r->id;
		}
	}
	if (is_numeric($options['direction'])) {
		if ($options['direction'] == '0') {
			$options['direction'] = 'horizontal';
		} else {
			$options['direction'] = 'vertical';
		}
	}
	$options['type'] = (int) $options['type'];
	$items = array();
	$menuid = $GLOBALS['fg_menus']++;
	$md5 = md5(
			$options['parent'] . '|0|' . json_encode($options)
	);
	$html = Core_cacheLoad('pages', 'fgmenu-' . $md5);
	if (1 || $html === false) {
		$html = menuBuild($options['parent'], 0, $options);
		Core_cacheSave('pages', 'fgmenu-' . $md5, $html);
	}
	switch ($options['type']) {
		case 2: // { tree
			$c.='<div class="menu-tree">' . $html . '</div>';
			break; // }
		case 1: // { accordion
			WW_addScript('/j/menu-accordion/menu.js');
			WW_addCSS('/j/menu-accordion/menu.css');
			$class = ( $options['state'] == 0 ) ? ' contracted' : (( $options['state'] == 1 ) ? ' expanded' : ' expand-selected');
			$c.= '<div class="menu-accordion' . $class . '">' . $html . '</div>';
			break; // }
		default: // { fly-out
			WW_addScript('/j/fg.menu/fg.menu.js');
			WW_addCSS('/j/fg.menu/fg.menu.css');
			$c.='<div class="menu-fg menu-fg-' . $options['direction'] . '" id="menu-fg-'
					. $menuid . '">' . $html . '</div>';
			if ($options['direction'] == 'vertical') {
				$posopts = "positionOpts: { posX: 'left', posY: 'top',"
						. "offsetX: 40, offsetY: 10, directionH: 'right', directionV: 'down',"
						. "detectH: true, detectV: true, linkToFront: false },";
			} else {
				$posopts = '';
			}
			WW_addInlineScript(
					"$(function(){ $('#menu-fg-$menuid>ul>li>a').each(function(){ $(this)"
					. ".fgmenu({ content:$(this).next().outerHTML(), choose:function(ev,ui"
					. "){ document.location=ui.item[0].childNodes(0).href; }, $posopts fly"
					. "Out:true }); }); $('.menu-fg>ul>li').addClass('fg-menu-top-level');"
					. "});"
			);
			break; // }
	}
	return $c;
}


